package com.ld.hpfs.web.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Const;
import com.ld.hpfs.common.utils.FileDigest;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.dao.UtilMapper;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.ExtReturn;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.UploadService;
import com.ld.hpfs.web.interseptor.WebConstants;

/**
 * 文件上传
 * 
 * @author bole
 * @date 2012-08-18 12:00:00
 */

@Controller
public class FileUploadController {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    
    @Autowired
    private UploadService       uploadService;
    @Autowired
    private UtilMapper          utilMapper;

    @ResponseBody
    @RequestMapping(value = "/uploadfiles", method = RequestMethod.POST)
    public void fileupload(@RequestParam(value = "upload_file", required = true) MultipartFile multipartFile,
            HttpSession session, HttpServletResponse httpServletResponse, HttpServletRequest request, PrintWriter writer) {
    	    HashMap<String,Object> result = new HashMap<String,Object>();
        try {
        	String value = request.getParameter("value") == null ? null : (String)request.getParameter("value");
            String fileMD5 = FileDigest.getFileMD5(multipartFile.getInputStream());
            String uploadFileName = multipartFile.getOriginalFilename();
            String fileType = StringUtils.substringAfterLast(uploadFileName, ".");
            logger.debug("文件的MD5：{}, 上传的文件名：{}, 文件后缀名：{}, 文件大小：{}",
                    new Object[] { fileMD5, StringUtils.substringBeforeLast(uploadFileName, "."), fileType,
                            multipartFile.getSize() });

            // String savePath =
            // request.getSession().getServletContext().getRealPath("/upload");
            // String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" +
            // File.separator + "dd");
            // String saveName = UUID.randomUUID().toString();
            String time = Tools.getCurrentDate();
            String localName = uploadFileName.replace("."+fileType, "")+"_"+time+"."+fileType;
            String savePath = Const.PROPERTIES.getProperty("import.server.dir", "c:\\upload");
            String finalPath = File.separator + localName;
            logger.debug("savePath:{}, finalPath:{}", new Object[] { savePath, finalPath });
            
            File saveFile = new File(savePath + finalPath);
            // 判断文件夹是否存在，不存在则创建
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            // 写入文件
            FileUtils.writeByteArrayToFile(saveFile, multipartFile.getBytes());
            
            if (convertSJJK0101(saveFile)) {
            	localName = localName.replace(".txt", ".xls");
            }

          //  String returnMsg = JackJson.fromObjectToJson(new ExtReturn(true, "Upload successfully!"));           
          //  writer.print(returnMsg);            
            result.put("resultcode",localName);
            
            User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
            if (user == null) {
	            Cookie cookie = new Cookie("JSESSIONID", "");
	            cookie.setMaxAge(0);
	            httpServletResponse.addCookie(cookie);
            }
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
        	if(result.get("resultcode")==null){
        		result.put("resultcode",9);
        	}
        	String returnMsg = JackJson.fromObjectToJson(result);
        	logger.debug("\n\n-------|UPLOAD|--------{}-------|UPLOAD|--------\n\n",returnMsg);
        	writer.print(returnMsg);
            writer.flush();
            writer.close();
        }
    }

    @RequestMapping(value = "/uploadalldone", method = RequestMethod.POST)
    public void uploadFinish(@RequestParam String[] filenames,@RequestParam String[] new_file_names,HttpSession session,
            HttpServletResponse httpServletResponse, HttpServletRequest request, PrintWriter writer) {
        HashMap<String,Object> result = new HashMap<String,Object>();
        try {        	
            User user = (User) session.getAttribute(WebConstants.CURRENT_USER);

            StringBuilder code = new StringBuilder();
            code.append(session.getAttribute(WebConstants.CURRENT_COMPANY)).append(user.getUserId()).append(System.currentTimeMillis());
            HashMap<String, Object> param = new HashMap<String, Object>();
            for(int i=0;i<filenames.length;i++){
            	param.put("file_str"+i, filenames[i]);
            	param.put("new_file_names"+i, new_file_names[i]);
            }
//            param.put("file_str", filenames);
//            param.put("new_file_names", new_file_names);
            param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY));
            param.put("type", WebConstants.IMPORT_TASK_TYPE_LOCAL_FILE);
            // User user =
            // (User)request.getSession().getAttribute(WebConstants.CURRENT_USER);               
            param.put("user_id", user.getUserId());
            param.put("create_time", Tools.getCurrentDay());
            param.put("status", WebConstants.TASK_STATUS_IMPORTED);
            param.put("code", code.toString());            
//             HashMap<String,Object> schemaId = utilMapper.getSchemaIdFromCompanyId(Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString()));           
//             	param.put("schemaId",schemaId.get("schema_id"));
             int ret = uploadService.insertImportLogTAX(param);
             if(ret == 0){
            	 String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
            	StringBuilder impUrl = new StringBuilder();
                impUrl.append(Const.PROPERTIES.getProperty("import.server.url"))
                        .append(Const.PROPERTIES.getProperty("import.server.import_method")).append(code.toString()).append("&lang=").append(lang);
                logger.debug("Import URL = {}", impUrl);
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(impUrl.toString());
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    try {
                        String res = EntityUtils.toString(entity);
                        logger.debug(res);
                        Map<String,Object> retMap = JackJson.fromJsonToObject(res, Map.class); 
                        String resultCode = retMap.get("ResultCode").toString(); 
                        System.out.println("resultCode======"+resultCode);
                        if(resultCode.equals("0")){
                  	       result.put("resultcode",0);
                            }else{
                         	   String resultMsg = retMap.get("ResultMsg").toString();
                  	           result.put("resultcode",resultMsg);
                           }
                    } finally {
                        instream.close();
                    }
                }
             } else {
             	result.put("resultcode",9);
             }
                
        } catch (HttpHostConnectException e) {
        	result.put("resultcode",98);
           
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
        	writer.print(JackJson.fromObjectToJson(result));
            writer.flush();
            writer.close();
        }
    }
    
    /*
     * 判断当前公司是否有导入方案
     */
    @RequestMapping(value = "/checkSchemeId")
    public void checkSchemeId(HttpSession session,HttpServletRequest request,HttpServletResponse response,PrintWriter writer){
    	response.setContentType("text/plain;charset=UTF-8");
    	HashMap<String,Object> result = new HashMap<String,Object>();
    	try{
    	HashMap<String,Object> schemaId = utilMapper.getSchemaIdFromCompanyId(Integer.parseInt(session.getAttribute(WebConstants.CURRENT_COMPANY).toString()));
    	if(schemaId == null){
        	result.put("resultcode",99);
    	}else{
    		result.put("resultcode",0);
    	}
      }catch (Exception e) {
          logger.error("Exception: {}", e);
      } finally {
      	writer.print(JackJson.fromObjectToJson(result));
          writer.flush();
          writer.close();
      }
    }

    /**
     * 得到用户的配置信息
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/getImportLog1", method = RequestMethod.GET)
    public void getImportLog1(ExtPager page, HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer) {
        HashMap<String, Object> param = new HashMap<String, Object>();
        HashMap<String, Object> result = new HashMap<String, Object>();
    //    String sort = (String) request.getParameter("sort") == null ? null : (String) request.getParameter("sort");
   //     String dir = (String) request.getParameter("dir") == null ? null : (String) request.getParameter("dir");
        response.setContentType("text/plain;charset=UTF-8");
        String status = request.getParameter("status") == null ? null : (String)request.getParameter("status");
        HashMap<String,Object> orderBy = new HashMap<String,Object>();
		orderBy.put("code", "IMPORT_CODE");
		orderBy.put("source", "SCHEME_TYPE");
		orderBy.put("sumlines", "ROW_NUMBER");
		orderBy.put("starttime", "START_TIME");
		orderBy.put("stoptime", "COMPLETE_TIME");
		orderBy.put("setting", "SCHEME_ID");
		orderBy.put("importuser", "CREATOR_ID");
		orderBy.put("status_name", "TASK_STATUS");
		orderBy.put("createtime", "CREATE_TIME");
		orderBy.put("taskdesc", "TASK_DESC");
        
        try {
            User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
            ArrayList<Map<String, String>> field = page.getSortField();
            StringBuffer sort = new StringBuffer("");
            if (user != null) {
                param.put("pageEnd", page.getStart() + page.getLimit());
                if(field!=null && field.size()>0){
					for(Map<String, String> map : field){
			        	sort.append(orderBy.get(map.get("property")) + " " + map.get("direction") + ",");
			        }
					param.put("orderBy", sort.substring(0,sort.length()-1));
				} else {
					param.put("orderBy", " CREATE_TIME desc");
				}
                param.put("pageStart", page.getStart());
                param.put("subOrder", " order by IMPORT_CODE");
                param.put("user_id", user.getUserId());
                param.put("company_id", session.getAttribute(WebConstants.CURRENT_COMPANY));
                param.put("status", status);
                String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
    			param.put("language", language);
                ArrayList<HashMap<String, Object>> logs = uploadService.getImportLog1(param);
                if (logs != null && logs.size() > 0) {
                    result.put("success", true);
                    result.put("total", param.get("pageCount"));
                    result.put("data", logs);
                } else {
                    result.put("success", true);
                    result.put("total", param.get("pageCount"));
                    result.put("data", "");
                }
                String returnMsg = JackJson.fromObjectToJson(result);
                logger.debug("{}", returnMsg);
                writer.print(returnMsg);
            } else {
                writer.print("");
            }
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }

    /**
     * 得到用户的配置信息
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/getImportLog2", method = RequestMethod.GET)
    public void getImportLog2(ExtPager page, HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer) {
        HashMap<String, Object> param = new HashMap<String, Object>();
        HashMap<String, Object> result = new HashMap<String, Object>();
    //    String sort = (String) request.getParameter("sort") == null ? null : (String) request.getParameter("sort");
   //     String dir = (String) request.getParameter("dir") == null ? null : (String) request.getParameter("dir");
        response.setContentType("text/plain;charset=UTF-8");
        String status = request.getParameter("status") == null ? null : (String)request.getParameter("status");
        HashMap<String,Object> orderBy = new HashMap<String,Object>();
		orderBy.put("code", "IMPORT_CODE");
		orderBy.put("source", "SCHEME_TYPE");
		orderBy.put("sumlines", "ROW_NUMBER");
		orderBy.put("starttime", "START_TIME");
		orderBy.put("stoptime", "COMPLETE_TIME");
		orderBy.put("setting", "SCHEME_ID");
		orderBy.put("importuser", "CREATOR_ID");
		orderBy.put("status_name", "TASK_STATUS");
		orderBy.put("createtime", "CREATE_TIME");
		orderBy.put("taskdesc", "TASK_DESC");
		orderBy.put("filename", "SCHEME_STR");
        try {
            User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
            ArrayList<Map<String, String>> field = page.getSortField();
            StringBuffer sort = new StringBuffer("");
            if (user != null) {
                param.put("pageEnd", page.getStart() + page.getLimit());
                if(field!=null && field.size()>0){
					for(Map<String, String> map : field){
			        	sort.append(orderBy.get(map.get("property")) + " " + map.get("direction") + ",");
			        }
					param.put("orderBy", sort.substring(0,sort.length()-1));
				} else {
					param.put("orderBy", " CREATE_TIME desc");
				}
                param.put("pageStart", page.getStart());
                param.put("subOrder", " order by IMPORT_CODE");
                param.put("user_id", user.getUserId());
                param.put("company_id", session.getAttribute(WebConstants.CURRENT_COMPANY));
                param.put("status", status);
                String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
    			param.put("language", language);
                ArrayList<HashMap<String, Object>> logs = uploadService.getImportLog2(param);
                if (logs != null && logs.size() > 0) {
                    result.put("success", true);
                    result.put("total", param.get("pageCount"));
                    result.put("data", logs);
                } else {
                    result.put("success", true);
                    result.put("total", param.get("pageCount"));
                    result.put("data", "");
                }
                String returnMsg = JackJson.fromObjectToJson(result);
                logger.debug("{}", returnMsg);
                writer.print(returnMsg);
            } else {
                writer.print("");
            }
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }
    
    /**
     * 得到用户的配置信息
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/getImportLog3", method = RequestMethod.GET)
    public void getImportLog3(ExtPager page, HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer) {
        HashMap<String, Object> param = new HashMap<String, Object>();
        HashMap<String, Object> result = new HashMap<String, Object>();
    //    String sort = (String) request.getParameter("sort") == null ? null : (String) request.getParameter("sort");
   //     String dir = (String) request.getParameter("dir") == null ? null : (String) request.getParameter("dir");
        response.setContentType("text/plain;charset=UTF-8");
        String status = request.getParameter("status") == null ? null : (String)request.getParameter("status");
        HashMap<String,Object> orderBy = new HashMap<String,Object>();
		orderBy.put("code", "IMPORT_CODE");
		orderBy.put("source", "SCHEME_TYPE");
		orderBy.put("sumlines", "ROW_NUMBER");
		orderBy.put("starttime", "START_TIME");
		orderBy.put("stoptime", "COMPLETE_TIME");
		orderBy.put("setting", "SCHEME_ID");
		orderBy.put("importuser", "CREATOR_ID");
		orderBy.put("status_name", "TASK_STATUS");
		orderBy.put("createtime", "CREATE_TIME");
		orderBy.put("taskdesc", "TASK_DESC");
        
        try {
            User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
            ArrayList<Map<String, String>> field = page.getSortField();
            StringBuffer sort = new StringBuffer("");
            if (user != null) {
                param.put("pageEnd", page.getStart() + page.getLimit());
                if(field!=null && field.size()>0){
					for(Map<String, String> map : field){
			        	sort.append(orderBy.get(map.get("property")) + " " + map.get("direction") + ",");
			        }
					param.put("orderBy", sort.substring(0,sort.length()-1));
				} else {
					param.put("orderBy", " CREATE_TIME desc");
				}
                param.put("pageStart", page.getStart());
                param.put("subOrder", " order by IMPORT_CODE");
                param.put("user_id", user.getUserId());
                param.put("company_id", session.getAttribute(WebConstants.CURRENT_COMPANY));
                param.put("status", status);
                String language = (String) session.getAttribute(WebConstants.CURRENT_LANG);
    			param.put("language", language);
                ArrayList<HashMap<String, Object>> logs = uploadService.getImportLog3(param);
                if (logs != null && logs.size() > 0) {
                    result.put("success", true);
                    result.put("total", param.get("pageCount"));
                    result.put("data", logs);
                } else {
                    result.put("success", true);
                    result.put("total", param.get("pageCount"));
                    result.put("data", "");
                }
                String returnMsg = JackJson.fromObjectToJson(result);
                logger.debug("{}", returnMsg);
                writer.print(returnMsg);
            } else {
                writer.print("");
            }
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }
    
    /**
     * 得到指定文件目录信息
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/getFileDirInfo", method = RequestMethod.GET)
    public void getFileDirInfo(ExtPager page, HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer) {
        // HashMap<String,Object> param = new HashMap<String,Object>();

        response.setContentType("text/plain;charset=UTF-8");
        HashMap<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("success", true);
            // boolean a=true;
            User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
            String code = uploadService.getCompanyCode((Integer)session.getAttribute(WebConstants.CURRENT_COMPANY));
            
            if (user != null) {
                ArrayList<HashMap<String, Object>> logs = uploadService.getFileDirInfo(
                        Tools.getPropertyValue("server.dir"), code, Integer.parseInt(user.getUserId()));
                if (logs != null && logs.size() > 0) {
                    result.put("children", logs);
                } else {
                    result.put("children", "");
                }
            } else {
                result.put("children", "");
            }
            String returnMsg = JackJson.fromObjectToJson(result);
            logger.debug("{}", returnMsg);
            writer.print(returnMsg);
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/ReLoadHardDiskFiles")
    public void ReLoadHardDiskFiles(ExtPager page, HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer) {
    	User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
    	String code = uploadService.getCompanyCode((Integer)session.getAttribute(WebConstants.CURRENT_COMPANY));
    	uploadService.ReLoadHardDiskFiles(Tools.getPropertyValue("server.dir"), code, Integer.parseInt(user.getUserId()));
    }
    
    @ResponseBody
    @RequestMapping(value = "/uploadserverfiles")
    public void serverfileupload(@RequestParam String[] itemIds,HttpSession session, HttpServletResponse httpServletResponse,
            HttpServletRequest request, PrintWriter writer) {

        try {
//            String itemIds = (String) request.getParameter("itemIds") == null ? null : (String) request
//                    .getParameter("itemIds");
        
            if (!Tools.isEmpty(itemIds)) {
                List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
                List<ArrayList<HashMap<String, Object>>> list2 = new ArrayList<ArrayList<HashMap<String, Object>>>();//服务器文件信息集合
                HashMap<String, Object> param = new HashMap<String, Object>();
                boolean Status_Success = false;
                for(String itemIds_test : itemIds){//因为传入的为数组，因此将每个元素作为一个信息源进行数据库查询
                	if(itemIds_test.length() < 1){
                		continue;
                	}
                	String[] ids = itemIds_test.split(",");
                    HashMap<String, String> map = new HashMap<String, String>();
                    param = new HashMap<String, Object>();
                    list = new ArrayList<HashMap<String, String>>();
                    for (int i = 0; i < ids.length; i++) {
                        map = new HashMap<String, String>();
                        map.put("id", ids[i]);
                        list.add(map);
                    }
                    param.put("list", list);
                    ArrayList<HashMap<String, Object>> files = uploadService.getUploadFileList(param);
                    list2.add(files);//查询到数据后，将数据插入到信息集合
                }
                for(ArrayList<HashMap<String, Object>> test_list : list2){//判断信息集合是否为空，非空可继续
                	if (test_list != null && test_list.size() > 0){
                		Status_Success = true;
                	}else{
                		Status_Success = false;
                	}
                }

                User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
                if (Status_Success) {
//                    String savePath = request.getSession().getServletContext().getRealPath("/upload");
//                    String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd");
//                    File saveFile = new File(savePath + File.separator + dataPath);
//                    if (!saveFile.exists()) {
//                        saveFile.mkdirs();
//                    }
                	StringBuffer filenames = new StringBuffer("");
                    for(int ia=0;ia<list2.size();ia++){
                    	filenames = new StringBuffer("");
                    	for(HashMap<String, Object> file : list2.get(ia)){//获取信息集合中每一个元素，并且获取元素中每个文件名并连接成字符串
                        	filenames.append(file.get("name") + ";");
                        }
                    
                    	param.put("file_str"+ia, filenames.substring(0, filenames.length() - 1));//插入到SCHEME_STR_X
                    	param.put("new_file_names"+ia, filenames.substring(0, filenames.length() - 1));//插入到LOCAL_FILE_X
              
                    }
                    
//                    for (HashMap<String, Object> file : files) {
////                        String finalPath = File.separator + dataPath + File.separator + file.get("name");
////                        copyfile(file.get("dir").toString(), savePath + finalPath);
//                        
//                    }

                    // TODO 保存文件信息到数据库，调用上传服务接口
                    StringBuilder code = new StringBuilder();
                    code.append(session.getAttribute(WebConstants.CURRENT_COMPANY)).append(user.getUserId()).append(System.currentTimeMillis());
//                    param = new HashMap<String, Object>();
                    
                    param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY));
                    param.put("type", WebConstants.IMPORT_TASK_TYPE_SERVER_FILE);
                    param.put("user_id", user.getUserId());
                    param.put("create_time", Tools.getCurrentDay());
                    param.put("status", WebConstants.TASK_STATUS_IMPORTED);
                    param.put("code", code.toString());
                    uploadService.insertImportLog(param);
                    String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
                    StringBuilder impUrl = new StringBuilder();
                    impUrl.append(Const.PROPERTIES.getProperty("import.server.url"))
                            .append(Const.PROPERTIES.getProperty("import.server.import_method")).append(code.toString()).append("&lang=").append(lang);
                    logger.debug("Import URL = {}", impUrl);
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpGet httpget = new HttpGet(impUrl.toString());
                    HttpResponse response = httpclient.execute(httpget);
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        InputStream instream = entity.getContent();
                        try {
                            String res = EntityUtils.toString(entity);
                            logger.debug(res);
                            Map<String,Object> retMap = JackJson.fromJsonToObject(res, Map.class); 
                            String resultCode = retMap.get("ResultCode").toString();   
                        } finally {
                            instream.close();
                        }
                    }
                }
            }
            
            HashMap<String, Object> result = new HashMap<String, Object>();
            result.put("resultcode", 0);
            String returnMsg = JackJson.fromObjectToJson(result);
            logger.debug("{}", returnMsg);
            writer.print(returnMsg);
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }

    private static void copyfile(String pathSrc, String pathDest) throws IOException {
        FileInputStream fi = new FileInputStream(pathSrc);

        FileOutputStream fo = new FileOutputStream(pathDest);

        byte data[] = new byte[fi.available()];

        fi.read(data);

        fo.write(data);

        fi.close();

        fo.close();
    }
    
    @ResponseBody
    @RequestMapping(value = "/checkPlan", method = RequestMethod.POST)
    public void checkPlan(@RequestParam String itemIds, HttpSession session,
            HttpServletResponse httpServletResponse, HttpServletRequest request, PrintWriter writer) {
        try {
        	String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
            StringBuilder impUrl = new StringBuilder();
            impUrl.append(Const.PROPERTIES.getProperty("import.server.url"))
                    .append(Const.PROPERTIES.getProperty("import.server.post_method")).append(itemIds).append("&lang=").append(lang);
            logger.debug("Import URL = {}", impUrl);
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(impUrl.toString());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            HashMap<String, Object> result = new HashMap<String, Object>();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    String res = EntityUtils.toString(entity);
                    logger.debug(res);
                    Map<String,Object> retMap = JackJson.fromJsonToObject(res, Map.class); 
                    result.put("msg", retMap.get("ResultMsg").toString());
                    result.put("resultcode", retMap.get("ResultCode").toString());
                } finally {
                    instream.close();
                }
            } else {
            	result.put("resultcode", 9);
            }
            String returnMsg = JackJson.fromObjectToJson(result);
            logger.debug("{}", returnMsg);
            writer.print(returnMsg);
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }
    
    
    @ResponseBody
    @RequestMapping(value = "/uncheckPlan", method = RequestMethod.POST)
    public void uncheckPlan(@RequestParam String itemIds, HttpSession session,
            HttpServletResponse httpServletResponse, HttpServletRequest request, PrintWriter writer) {
        try {
        	String lang = session.getAttribute(WebConstants.CURRENT_LANG).toString();
            StringBuilder impUrl = new StringBuilder();
            impUrl.append(Const.PROPERTIES.getProperty("import.server.url"))
                    .append(Const.PROPERTIES.getProperty("import.server.unpost_method")).append(itemIds).append("&lang=").append(lang);
            logger.debug("Import URL = {}", impUrl);
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(impUrl.toString());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            HashMap<String, Object> result = new HashMap<String, Object>();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    String res = EntityUtils.toString(entity);
                    logger.debug(res);
                    Map<String,Object> retMap = JackJson.fromJsonToObject(res, Map.class); 
                    result.put("msg", retMap.get("ResultMsg").toString());
                    result.put("resultcode", retMap.get("ResultCode").toString());
                } finally {
                    instream.close();
                }
            } else {
            	result.put("resultcode", 9);
            }
            String returnMsg = JackJson.fromObjectToJson(result);
            logger.debug("{}", returnMsg);
            writer.print(returnMsg);
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }
    
    /**
     * 删除批次
     *     
     */
    @RequestMapping(value = "/deletePlanCode")
    public void deletePlanCode(ExtPager page, HttpSession session, HttpServletRequest request,
            HttpServletResponse response, PrintWriter writer) {
    	String code = request.getParameter("code") == null ? null : (String)request.getParameter("code");
         HashMap<String,Object> param = new HashMap<String,Object>();

        response.setContentType("text/plain;charset=UTF-8");
        HashMap<String, Object> result = new HashMap<String, Object>();
        try {
        	String company_id = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
        	User user = (User)session.getAttribute(WebConstants.CURRENT_USER);
        	param.put("batch_no", code);
        	param.put("cpn_id", company_id);
        	param.put("user_id", user.getUserId());       	
        	int ret = uploadService.deletePlanCode(param);
			if(ret == 0){
				result.put("resultcode",0);
			}else{
				result.put("resultcode",9);
			}			
		   writer.print(JackJson.fromObjectToJson(result));
        } catch (Exception e) {
            logger.error("Exception: {}", e);
        } finally {
            writer.flush();
            writer.close();
        }
    }
    
    @RequestMapping(value = "/getLocalFileTitle")
    public void getLocalFileTitle(HttpSession session,
            HttpServletResponse httpServletResponse, HttpServletRequest request, PrintWriter writer){
    	HashMap<String,Object> param = new HashMap<String,Object>();
    	try{
        	param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
        	ArrayList<HashMap<String, Object>> TitleInfo = uploadService.getLocalFileTitle(param);
        	String returnMsg = JackJson.fromObjectToJson(TitleInfo);
            logger.debug("{}", returnMsg);
            writer.print(returnMsg);
    	}catch(Exception e){
    		logger.error("Exception: {}", e);
    	}finally{
    		writer.flush();
            writer.close();
    	}
    }
    
    @RequestMapping(value = "/setLabelName",method = RequestMethod.POST)
    @ResponseBody
    public Object setLabelName(HttpSession session, HttpServletRequest request){
    	HashMap<String,Object> param = new HashMap<String,Object>();
    	try{
    		String  TITLE1 = request.getParameter("Title1") == null ? null : (String)request.getParameter("Title1");
    		String  TITLE2 = request.getParameter("Title2") == null ? null : (String)request.getParameter("Title2");
    		String  TITLE3 = request.getParameter("Title3") == null ? null : (String)request.getParameter("Title3");
    		String  TITLE4 = request.getParameter("Title4") == null ? null : (String)request.getParameter("Title4");
    		String  TITLE5 = request.getParameter("Title5") == null ? null : (String)request.getParameter("Title5");
    		
    		param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
    		param.put("TITLE1", TITLE1);
    		param.put("TITLE2", TITLE2);
    		param.put("TITLE3", TITLE3);
    		param.put("TITLE4", TITLE4);
    		param.put("TITLE5", TITLE5);
    		
    		int Ret = uploadService.setLabelName(param);
    		
    		if(Ret == -1){
    			return new ExtReturn(false, "修改本地导入文件标题失败");
    		}
    	}catch(Exception e){
    		logger.error("Exception: {}", e);
    	}
    	return new ExtReturn(true, "success");
    }

    private static void exportOneRow(String[] header, String[] detail, HSSFSheet sheet, int rowIndex) throws Exception {
        HSSFRow row = sheet.createRow(rowIndex);
        HSSFCell cell;

        int columnIndex = 0;
        for (String column : header) {
            cell = row.createCell(columnIndex);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(column);
            columnIndex++;
        }

        for (String column : detail) {
        	System.out.println("*********************");
        	System.out.println(column);
            cell = row.createCell(columnIndex);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(column);
            columnIndex++;
        }
    }
    private static boolean convertSJJK0101(File file) throws Exception {
    	boolean executed = false;
        if (file != null && file.getName().endsWith(".txt")) {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gb2312"));
            try {
            	
                String data = br.readLine();
                if (data != null && data.trim().equalsIgnoreCase("SJJK0101")) {
                    HSSFWorkbook wb = new HSSFWorkbook();
                    HSSFSheet sheet = wb.createSheet();
                    int rowIndex = 0;

                    String[] temp;
                    String[] header = null;
                    String[] detail;

                    while ((data=br.readLine()) != null ) {
                        temp = data.split("~~");
                        if (temp.length == 13) {
                            detail = temp;
                            exportOneRow(header, detail, sheet, rowIndex++);
                        } else {
                            header = temp;
                        }

                    }

                    String newFilePath = file.getAbsolutePath().replace(".txt", ".xls");
                    FileOutputStream fOut = new FileOutputStream(newFilePath);
                    wb.write(fOut);
                    fOut.flush();
                    fOut.close();
                    executed = true;
                }
                br.close();
            } catch (Exception e) {
                throw e;
            }
        }
        return executed;
    }
}
